package com.controller;

import com.entity.Employee;
import com.entity.Result;
import com.service.EmployeeService;
import com.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/login")
    public Result login(String ename, String password, String verify, String uuid, HttpServletResponse response){
        String code = (String)redisTemplate.opsForValue().get("code:" + uuid);

        if(code.equals(verify)){
            //验证码正确
            Employee employee = employeeService.login(ename, password);
            //生成token
            String token = JwtUtil.create(employee.getEid(), employee.getEname());
            //将token存入redis中
            redisTemplate.opsForValue().set("token:" + token, "xxx", 60*24, TimeUnit.MINUTES);

            //token存入响应头
            response.setHeader("token", token);

            //前后端分离的项目，必须暴露响应头，否则前端收不到响应头
            response.setHeader("Access-Control-Expose-Headers", "*");

            return Result.ok("登录成功");
        }else {
            //验证码错误
            return new Result(404, "验证码错误", null);
        }
    }
    @RequestMapping("/find")
    public Result findAdmin(){
        List<Employee> employees = employeeService.find();
        return new Result<>(200,"查询成功",employees);
    }

    @RequestMapping("/findEname")
    public Result findEname(HttpServletRequest request){
        String token = request.getHeader("token");
        String ename = JwtUtil.getEname(token);
        return Result.ok(ename);
    }
}
